package com.sto.stoapp.upload;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.db.manager.UploadDataManager;
import com.sto.stoapp.http.request.ServerSmsUploadRequest;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.AlarmAlertWakeLockManager;
import com.sto.stoapp.manager.UnSentDataManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.thread.ServerSmsUploadThread;
import com.sto.stoapp.thread.SignHelpSmsThread;
import com.sto.stoapp.thread.SimpleLoginThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;

import java.util.ArrayList;

import static com.sto.stoapp.status.EnumTableNames.STATUS_TABLE_SALESMAN_HELP_SIGN;

/**
 * 上传数据服务
 * 
 * @author buangbing
 * 
 */
public class UploadDataService extends Service {

	// 广播更新事件
	private final int UPDATE_BROAD_CAST = 0xfd;
	private final int NO_DATA_TO_UP = 3;


	private UploadBroad uploadBroad;

	private boolean is_upload = false;
	private String againDate;

	private String orderResp;

	public final String SYNCH = "synch";
	// 服务器返回成功
	public final static String SUCCESS = "000";
	// 服务器返回失败
	public final static String ERROR = "error";

	public final static String OK_RECV = "OK_RECV";
	// 没有数据要发送
	public final static String NO_DATAS = "no_datas";

	private int count = 0;

	private ArrayList<EnumTableNames> tableList = new ArrayList<EnumTableNames>();

	@Override
	public void onCreate() {
		super.onCreate();
		uploadBroad = new UploadBroad();
		IntentFilter filter = new IntentFilter(UnifiedStaticType.UP_ACTION);
		registerReceiver(uploadBroad, filter);

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@SuppressLint("HandlerLeak")
	private Handler recvHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			EnumTableNames status = EnumTableNames.values()[msg.what];
			switch (status) {
			// 业务员-收件
			case STATUS_TABLE_SALESMAN_RECEIVE:
				// 业务员-签收
			case STATUS_TABLE_SALESMAN_SIGN:
				// 问题件
			case STATUS_TABLE_PROBLEM:
				// 订单提取
			case STATUS_TABLE_SALESMAN_ORDER_EXTRACT:
				// 订单打回
			case STATUS_TABLE_SALESMAN_ORDER_BACK:
				// 服务点短信
			case STATUS_TABLE_SERVICE_SMS:
				// 扫描员-收件
			case STATUS_TABLE_SCANNING_RECEIVE:
				// 扫描员-发件
			case STATUS_TABLE_SCANNING_SENDPIECE:
				// 扫描员-到件
			case STATUS_TABLE_SCANNING_REACHPIECE:
				// 扫描员-派件
			case STATUS_TABLE_SCANNING_ASSIGNPIECE:
				// 留仓件
			case STATUS_TABLE_STAY_WAREHOURSE:
				// 装袋&发件
			case STATUS_TABLE_BAGGINGADNSENDPIECE:
				// 装车发件
			case STATUS_TABLE_LOADCAR_SENDPIECE:
				// 发车扫描
			case STATUS_TABLE_SEND_CAR:
				// 到车扫描
			case STATUS_TABLE_RECEIVE_CAR:
				// 中转到件
			case STATUS_TABLE_CENTER_REACHPIECE:
				// 中转发件
			case STATUS_TABLE_CENTER_SENDPIECE:
				// 中转-留仓件
			case STATUS_TABLE_CENTER_STAY_WAREHOURSE:
				// 中转-装袋&发件
			case STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE:
				// 中转-装车发件
			case STATUS_TABLE_CENTER_LOADCAR_SENDPIECE:
				// 中转-发车扫描
			case STATUS_TABLE_CENTER_SEND_CAR:
				// 中转-到车扫描
			case STATUS_TABLE_CENTER_RECEIVE_CAR:
				// 航空-提货员-到包扫描
			case STATUS_TABLE_AVIATION_PICKER_PACKET:
				// 航空-扫描-到件
			case STATUS_TABLE_AVIATION_SCAN_TO_PIECE:
				// // 航空-扫描-发件-指定路由号发件
				// case STATUS_TABLE_AVIATION_SCAN_SEND_ROUTE:
				// 航空-扫描-发件
			case STATUS_TABLE_AVIATION_SCAN_SEND:
				// 航空-扫描-问题件
			case STATUS_TABLE_AVIATION_PROBLEM:
				// 航空-扫描-留仓件
			case STATUS_TABLE_AVIATION_STAY_WAREHOURSE:
				// 航空-扫描-包操作-装包&发件
			case STATUS_TABLE_AVIATION_SCAN_PACKET_SEND:
				// 航空-扫描-包操作-发包
			case STATUS_TABLE_AVIATION_SCAN_SEND_BAG:
				// 航空-扫描-包操作-到包
			case STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG:
				// 航空-扫描-装车发件
			case STATUS_TABLE_AVIATION_LOADCAR_SENDPIECE:
				// 航空-扫描-发车扫描
			case STATUS_TABLE_AVIATION_SEND_CAR:
				// 航空-扫描-到车扫描
			case STATUS_TABLE_AVIATION_RECEIVE_CAR:
				// 交接扫描
			case STATUS_TABLE_JOIN_SCAN:
				// 袋操作
			case STATUS_TABLE_SCANNING_BAGGING_OPERATE:
				// 铅封操作
			case STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE:
				// 中专袋操作
			case STATUS_CENTER_TABLE_BAGGING_OPERATE:

				// 中转铅封
			case STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE:
				// 航空铅封
			case STATUS_TABLE_AVIATION_LEAD_SEALING_OPERATE:
				// 航空包操
			case STATUS_TABLE_AVIATION_PACKAGE_OPERATE:
				//Add by wj 代收签收的回调
			case STATUS_TABLE_SALESMAN_HELP_SIGN:

				if (msg.obj.toString().contains(SUCCESS)
						|| msg.obj.toString().contains(OK_RECV)) {
					// 修改发送状态
					int sendCount = UploadDataManager.getInstance(
							UploadDataService.this).UpdateSendState(status);

					UnSentDataManager.getInstance().deleteCodeNumber(sendCount);
					sendUnSendCountBoard(sendCount);
					if (tableList.size() > 0) {
						count = UploadDataManager.getInstance(
								UploadDataService.this)
								.StatisticsUnsendDataCount(tableList.get(0));
					}
					if (count == 0) {
						Helper.showToast(
								UploadDataService.this,
								getString(Integer.parseInt(tableList.get(0)
										.getScanTypeName()))
										+ getString(R.string.send_success));
					}

				} else if (msg.obj.toString().contains(ERROR)) {
					count = 0;
					Helper.showToast(
							UploadDataService.this,
							getString(Integer.parseInt(status.getScanTypeName()))
									+ getString(R.string.send_fail));
				} else {
					count = 0;
					tableList.clear();
					is_upload = false;
					Helper.showToast(
							UploadDataService.this,
							getString(Integer.parseInt(status.getScanTypeName()))
									+ getString(R.string.connect_service_fail));
				}

				break;
			// 修改时间上传
			case STATUS_TABLE_MODIFY_TIME_SYN:
				UploadDataManager.getInstance(UploadDataService.this)
						.UpdateSendState(status);
				break;

			default:
				break;
			}

			synchronized (SYNCH) {
				try {
					SYNCH.notify(); // 恢复线程
				} catch (Exception e) {
					e.printStackTrace();
					ExceptionLog.writeLog("recvHandler", e.getMessage());
				}
			}

		}
	};

	@SuppressLint("HandlerLeak")
	private Handler broadHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == UPDATE_BROAD_CAST) {
				ArrayList<Integer> uploadList = new ArrayList<Integer>();
				try {
					uploadList = (ArrayList<Integer>) msg.obj;
					if (uploadList.size() <= 0) {
						return;
					}
					for (Integer status : uploadList) {
						if (!tableList.contains(status)) {
							tableList.add(EnumTableNames.values()[status]);
						}
						// 该列表数据正在发送
						else {
							Helper.showToast(
									UploadDataService.this,
									UploadDataService.this.getText(
											R.string.upload_requesting)
											.toString());
						}
					}
					new DoUploadThread(UploadDataService.this, broadHandler)
							.start();
				} catch (Exception e) {
					e.printStackTrace();
					ExceptionLog.writeLog("broadHandler", e.getMessage());
				}
			}
			if (msg.what == NO_DATA_TO_UP) {
				Helper.showToast(UploadDataService.this, "已启用数据上传");
			}
		}
	};

	// private static int codeCount = 1;
	// private String code = "568592253935";

	class DoUploadThread extends BaseThread {
		private Context context;
		private Handler h;

		public DoUploadThread(Context context, Handler h) {
			super(context);
			this.context = context;
			this.h = h;
		}

		@Override
		public void run() {
			super.run();

			// 上传之前先登录'
			SimpleLoginThread simpleLoginThread = new SimpleLoginThread(context);
			try {
				simpleLoginThread.start();
				simpleLoginThread.join();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			int length = tableList.size();
			// int unsendCount = 0;
			Log.d("DownThread=", "" + length);

			if (length > 0 && !is_upload) {
				// 锁定cpu不让进入待机
				AlarmAlertWakeLockManager.acquireCpuWakeLock(context, "upload");
				is_upload = true;

				// 重传
				if (againDate != null) {
					int againCount = UploadDataManager.getInstance(
							UploadDataService.this).UpdateAgainUploadStatus(
							tableList.get(0), againDate);
					UnSentDataManager.getInstance().deleteCodeNumber(
							(0 - againCount));
				}

				count = UploadDataManager.getInstance(context)
						.StatisticsUnsendDataCount(tableList.get(0));
				h.obtainMessage(NO_DATA_TO_UP).sendToTarget();
				// 订单回执
				if (orderResp != null) {

					count = 1;
				}

				do {
					if (count > 0) {
						switch (tableList.get(0)) {
						case STATUS_TABLE_SERVICE_SMS:
							ServerSmsUploadRequest Request = new ServerSmsUploadRequest();
							Request.setData(UploadDataManager.getInstance(
									context).queryUploadSmsData(
									tableList.get(0)));

							ServerSmsUploadThread SmsThread = new ServerSmsUploadThread(
									context, tableList.get(0), Request,
									recvHandler);

							SmsThread.start();
							break;

						case STATUS_TABLE_SALESMAN_ORDER_EXTRACT:

							UploadOrderGainDataThread uploadOrderGainDataThread = new UploadOrderGainDataThread(
									context,
									EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT,

									recvHandler);
							uploadOrderGainDataThread.start();

							break;
						case STATUS_TABLE_SALESMAN_ORDER_BACK:
							UploadOrderBackThread orderBackThread = new UploadOrderBackThread(
									context,
									EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_BACK,

									recvHandler);
							orderBackThread.start();
							break;

						//Add by wj 代收签收短信
						case STATUS_TABLE_SALESMAN_HELP_SIGN:

							SignHelpSmsThread signHelpSmsThread=new SignHelpSmsThread(
									context,
									recvHandler,
									STATUS_TABLE_SALESMAN_HELP_SIGN);
							signHelpSmsThread.start();

							break;

						default:

							UploadDataThread uploadDataThread = new UploadDataThread(
									context, tableList.get(0),

									recvHandler);
							uploadDataThread.start();
							break;
						}

						synchronized (SYNCH) {
							try {
								SYNCH.wait(); // 暂停线程
							} catch (InterruptedException e) {
								e.printStackTrace();
								ExceptionLog.writeLog("DownThread",
										e.getMessage());
								is_upload = false;
							}
						}
					}

					else {
						tableList.remove(0);
						if (tableList.size() <= 0) {

							is_upload = false;
						} else {
							count = UploadDataManager
									.getInstance(context)
									.StatisticsUnsendDataCount(tableList.get(0));
						}
					}

				} while (is_upload);
				AlarmAlertWakeLockManager.releaseCpuLock("upload");

			}

		}
	}

	private void showMsg(final String text) {
		recvHandler.post(new Runnable() {

			@Override
			public void run() {
				Helper.showToast(UploadDataService.this, text);
			}
		});
	}

	class UploadBroad extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(UnifiedStaticType.UP_ACTION)) {
				if (!Helper.isNetworkAvailable(context)) {
					Helper.showToast(context, "网络不可用，上传失败，请检查网络。");
					return;
				}
				againDate = null;
				Message msg = broadHandler.obtainMessage();
				msg.what = UPDATE_BROAD_CAST;
				// msg.obj = intent
				// .getParcelableArrayListExtra(UnifiedStaticType.UPLOAD_TYPE);
				msg.obj = intent
						.getIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE);
				againDate = intent
						.getStringExtra(UnifiedStaticType.AGAIN_UPLOAD_DATE);
				orderResp = intent
						.getStringExtra(UnifiedStaticType.UPLOAD_ORDER_RESP);
				broadHandler.sendMessage(msg);
			}
		}
	}

	/**
	 * 更新未发送数据
	 */
	private void sendUnSendCountBoard(int sendCount) {

		sendCount = 0;
		Intent intent = new Intent(BaseActivity.SEND_ACTION);
		intent.putExtra(BaseActivity.SEND_COUNT, sendCount);
		sendBroadcast(intent);
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(uploadBroad);
		broadHandler.removeMessages(UPDATE_BROAD_CAST);

		super.onDestroy();
	}
}
